package org.csu.mypetstore.web.servlets;

import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.domain.Item;
import org.csu.mypetstore.domain.Product;
import org.csu.mypetstore.service.CatalogService;
import org.csu.mypetstore.service.LogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

public class ViewItemServlet extends HttpServlet {
    private static final String VIEW_Item = "/WEB-INF/jsp/catalog/Item.jsp";
    private String itemId = null;
    boolean isItemInStock = true;
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        itemId = req.getParameter("itemId");

        CatalogService service = new CatalogService();
        Item item = service.getItem(itemId);
        isItemInStock = service.isItemInStock(itemId);

        HttpSession session = req.getSession();
        session.setAttribute("item",item);


        Account account = (Account)session.getAttribute("account");
        if(account != null){
            HttpServletRequest httpRequest= req;
            String strBackUrl = "http://" + req.getServerName() + ":" + req.getServerPort()
                    + httpRequest.getContextPath() + httpRequest.getServletPath() + "?" + (httpRequest.getQueryString());

            LogService logService = new LogService();

            String logInfo = logService.logInfo(" ") + strBackUrl + " 观看商品" + itemId;
            logService.insertLogInfo(account.getUsername(), logInfo);
        }

        req.getRequestDispatcher(VIEW_Item).forward(req,resp);
    }
}
